'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { ToolCard } from '@/components/tools/tool-card'
import { LoadingState } from '@/components/ui/loading-spinner'
import { Heart, Search, Filter, Grid, List } from 'lucide-react'

interface FavoriteTool {
  id: string
  title: string
  description: string
  url: string
  image?: string
  category: {
    id: string
    name: string
    icon: string
  }
  user: {
    name: string
  }
  createdAt: string
  favoriteDate: string
}

export default function FavoritesPage() {
  const { user, loading: authLoading } = useAuth()
  const [favorites, setFavorites] = useState<FavoriteTool[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState('')
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
  const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'name'>('newest')

  useEffect(() => {
    if (!authLoading && user) {
      fetchFavorites()
    }
  }, [user, authLoading])

  const fetchFavorites = async () => {
    try {
      setLoading(true)
      setError(null)

      const response = await fetch('/api/user/favorites', {
        headers: {
          'Authorization': 'Bearer dev-user', // 开发环境临时认证
          'Content-Type': 'application/json'
        }
      })

      const result = await response.json()

      if (response.ok) {
        setFavorites(result.data || [])
      } else {
        setError(result.error || '获取收藏失败')
      }
    } catch (err) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  const removeFavorite = async (toolId: string) => {
    try {
      const response = await fetch(`/api/user/favorites/${toolId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': 'Bearer dev-user',
          'Content-Type': 'application/json'
        }
      })

      if (response.ok) {
        setFavorites(prev => prev.filter(fav => fav.id !== toolId))
      } else {
        alert('取消收藏失败')
      }
    } catch (error) {
      alert('取消收藏失败')
    }
  }

  // 筛选和排序
  const filteredFavorites = favorites
    .filter(fav => {
      const matchesSearch = !searchQuery || 
        fav.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        fav.description.toLowerCase().includes(searchQuery.toLowerCase())
      
      const matchesCategory = !selectedCategory || fav.category.id === selectedCategory
      
      return matchesSearch && matchesCategory
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'newest':
          return new Date(b.favoriteDate).getTime() - new Date(a.favoriteDate).getTime()
        case 'oldest':
          return new Date(a.favoriteDate).getTime() - new Date(b.favoriteDate).getTime()
        case 'name':
          return a.title.localeCompare(b.title)
        default:
          return 0
      }
    })

  // 获取所有分类
  const categories = Array.from(new Set(favorites.map(fav => fav.category.id)))
    .map(id => favorites.find(fav => fav.category.id === id)?.category)
    .filter(Boolean)

  if (authLoading) {
    return <LoadingState message="验证登录状态..." />
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <Heart className="h-16 w-16 text-gray-400 mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-gray-900 mb-2">请先登录</h1>
          <p className="text-gray-600 mb-4">登录后即可查看您的收藏</p>
          <a
            href="/login?redirect=/favorites"
            className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
          >
            立即登录
          </a>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-6 lg:py-8">
        {/* 页面标题 */}
        <div className="mb-6 sm:mb-8">
          <div className="flex items-center gap-3 mb-2">
            <Heart className="h-8 w-8 text-red-500" />
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">我的收藏</h1>
          </div>
          <p className="text-sm sm:text-base text-gray-600">
            您收藏的工具和资源 ({favorites.length} 个)
          </p>
        </div>

        {/* 搜索和筛选 */}
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {/* 搜索框 */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
              <input
                type="text"
                placeholder="搜索收藏的工具..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>

            {/* 分类筛选 */}
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="">所有分类</option>
              {categories.map((category) => (
                <option key={category!.id} value={category!.id}>
                  {category!.icon} {category!.name}
                </option>
              ))}
            </select>

            {/* 排序 */}
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as any)}
              className="px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="newest">最新收藏</option>
              <option value="oldest">最早收藏</option>
              <option value="name">按名称排序</option>
            </select>

            {/* 视图模式 */}
            <div className="flex border border-gray-300 rounded-md">
              <button
                onClick={() => setViewMode('grid')}
                className={`flex-1 flex items-center justify-center py-2 px-3 ${
                  viewMode === 'grid' 
                    ? 'bg-blue-500 text-white' 
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                }`}
              >
                <Grid className="h-4 w-4" />
              </button>
              <button
                onClick={() => setViewMode('list')}
                className={`flex-1 flex items-center justify-center py-2 px-3 ${
                  viewMode === 'list' 
                    ? 'bg-blue-500 text-white' 
                    : 'bg-white text-gray-700 hover:bg-gray-50'
                }`}
              >
                <List className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>

        {/* 收藏列表 */}
        {loading ? (
          <LoadingState message="加载收藏中..." />
        ) : error ? (
          <div className="text-center py-12">
            <Heart className="h-16 w-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">加载失败</h3>
            <p className="text-gray-600 mb-4">{error}</p>
            <button
              onClick={fetchFavorites}
              className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
            >
              重试
            </button>
          </div>
        ) : filteredFavorites.length === 0 ? (
          <div className="text-center py-12">
            <Heart className="h-16 w-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              {searchQuery || selectedCategory ? '没有找到匹配的收藏' : '暂无收藏'}
            </h3>
            <p className="text-gray-600 mb-4">
              {searchQuery || selectedCategory 
                ? '尝试调整搜索条件或筛选器' 
                : '去发现一些有趣的工具并收藏它们吧！'
              }
            </p>
            {!searchQuery && !selectedCategory && (
              <a
                href="/"
                className="inline-flex items-center px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
              >
                浏览工具
              </a>
            )}
          </div>
        ) : (
          <div className={
            viewMode === 'grid' 
              ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'
              : 'space-y-4'
          }>
            {filteredFavorites.map((tool) => (
              <div key={tool.id} className="relative">
                <ToolCard tool={tool} />
                <button
                  onClick={() => removeFavorite(tool.id)}
                  className="absolute top-2 right-2 p-2 bg-white rounded-full shadow-md hover:bg-red-50 transition-colors"
                  title="取消收藏"
                >
                  <Heart className="h-4 w-4 text-red-500 fill-current" />
                </button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
